package mvc.controller;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.annotation.Controller;
import mvc.util.GetPackageClass;


public class DispacherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String path = request.getServletPath();
			String pathM = this.getPath(path).replace("/", "");
			String basePackage = (String)this.getServletContext().getAttribute("basePackage");
			Set<Class<?>> classes =  GetPackageClass.getClasses(basePackage);
			for(Class<?> cl : classes){
				if(cl.isAnnotationPresent(Controller.class)){
					Controller cont = cl.getAnnotation(Controller.class);
					String mapp = cont.value();
					if(mapp.equals(pathM)){
						Object ob = cl.newInstance();
						Field[] fileds = cl.getDeclaredFields();
						for(Field fl : fileds){
							Class<?> cla = fl.getType();
							Object fOb = cla.newInstance();
							Field[] fls = cla.getDeclaredFields();
							for(Field ld : fls){
								ld.setAccessible(true);
								ld.set(fOb,request.getParameter(ld.getName()));
								ld.setAccessible(false);
							}
							fl.setAccessible(true);
							fl.set(ob, fOb);
						}
						Method eMethod = cl.getMethod("excute", new Class[]{});
						Object obje = eMethod.invoke(ob, new Object[]{});
						Map<String,String> maps = (Map<String,String>)obje;
						String key = maps.keySet().iterator().next();
						String value = maps.get(key);
						request.setAttribute("mess", value);
					    RequestDispatcher dis = request.getRequestDispatcher("/view/" + key + ".jsp");
					    dis.forward(request, response);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}


		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
   
	
	private String getPath(String serveletPath){
		return serveletPath.split("\\.")[0];
	}
}
